import { message } from "antd";
import axios from "axios";
import { KEY_REQUEST_TOKEN, KEY_STORE_TOKEN } from './constant';

const http = axios.create()

// 请求
http.interceptors.request.use(
    config => {
        let token = window.localStorage.getItem(KEY_STORE_TOKEN)
        config.headers[KEY_REQUEST_TOKEN] = !!token ? token : ""
        config.baseURL = '/'
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应
http.interceptors.response.use(
    res => {
        const { newToken } = res.headers
        if (!!newToken) {
            console.info("新 token", newToken)
            window.localStorage.setItem(KEY_STORE_TOKEN, newToken)
            http.defaults.headers.common[KEY_REQUEST_TOKEN] = newToken
        }
        return res
    },
    error => {
        if (error.response.status == 401) {
            window.localStorage.removeItem(KEY_STORE_TOKEN)
            if (window.location.pathname == "/login") {
                return Promise.reject(error)
            }
            window.location.href = "/login"
        } else {
            const data = error.response.data
            console.info(data)
            if (data.message) {
                message.error(data.message)
            }
            return Promise.reject(error)
        }
    }
)

export default http